package com.anyou.mall.sho.service.impl;

import java.util.Date;
import java.util.List;

import com.anyou.common.core.domain.ApiResult;
import com.anyou.common.core.domain.entity.SysUser;
import com.anyou.common.exception.GlobalException;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.StringUtils;
import com.anyou.common.utils.uuid.RandomKit;
import com.anyou.mall.platform.service.IPlaPlatformSettingsService;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.domain.CarPartsShopAudit;
import com.anyou.mall.sho.mapper.CarPartsShopAuditMapper;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.anyou.mall.sho.param.IsPassCarPartsShopAuditParam;
import com.anyou.mall.sho.param.IsPassCarPartsShopCertAudit;
import com.anyou.mall.sho.service.ICarPartsShopAuditService;
import com.anyou.mall.sho.service.ICarPartsShopService;
import com.anyou.mall.sho.service.IShopNoticeService;
import com.anyou.mall.sho.vo.CarPartsShopAuditListVo;
import com.anyou.mall.store.entity.Store;
import com.anyou.mall.store.service.IStoreService;
import com.anyou.mall.use.domain.User;
import com.anyou.mall.use.domain.UserAuditNotice;
import com.anyou.mall.use.domain.UserNotice;
import com.anyou.mall.use.service.IUserAuditNoticeService;
import com.anyou.mall.use.service.IUserNoticeService;
import com.anyou.mall.use.service.IUserService;
import com.anyou.system.domain.SysUserRole;
import com.anyou.system.mapper.SysUserRoleMapper;
import com.anyou.system.service.ISysUserService;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 汽配商入住审核Service业务层处理
 *
 * @author gaochaohao
 * @date 2022-03-18
 */
@Service
public class CarPartsShopAuditServiceImpl  extends ServiceImpl<CarPartsShopAuditMapper, CarPartsShopAudit> implements ICarPartsShopAuditService
{
    @Autowired
    private CarPartsShopAuditMapper carPartsShopAuditMapper;
    @Autowired
    private IShopNoticeService shopNoticeService;
    @Autowired
    private IPlaPlatformSettingsService plaPlatformSettingsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private ICarPartsShopService carPartsShopService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IUserAuditNoticeService userAuditNoticeService;

    @Autowired
    private IUserNoticeService userNoticeService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${adminUrl}")
    private String adminUrl;//后台管理页面地址



    /**
     * 查询汽配商入住审核
     *
     * @param carPartsShopAuditId 汽配商入住审核主键
     * @return 汽配商入住审核
     */
    @Override
    public CarPartsShopAudit selectCarPartsShopAuditByCarPartsShopAuditId(Long carPartsShopAuditId)
    {
        return carPartsShopAuditMapper.selectCarPartsShopAuditByCarPartsShopAuditId(carPartsShopAuditId);
    }

    /**
     * 查询汽配商入住审核列表
     *
     * @param carPartsShopAudit 汽配商入住审核
     * @return 汽配商入住审核
     */
    @Override
    public List<CarPartsShopAuditListVo> selectCarPartsShopAuditList(CarPartsShopAudit carPartsShopAudit)
    {
        return carPartsShopAuditMapper.selectCarPartsShopAuditList(carPartsShopAudit);
    }

    /**
     * 新增汽配商入住审核
     *
     * @param carPartsShopAudit 汽配商入住审核
     * @return 结果
     */
    @Override
    public int insertCarPartsShopAudit(CarPartsShopAudit carPartsShopAudit)
    {
        carPartsShopAudit.setCreateTime(DateUtils.getNowDate());
        return carPartsShopAuditMapper.insertCarPartsShopAudit(carPartsShopAudit);
    }

    /**
     * 修改汽配商入住审核
     *
     * @param carPartsShopAudit 汽配商入住审核
     * @return 结果
     */
    @Override
    public int updateCarPartsShopAudit(CarPartsShopAudit carPartsShopAudit)
    {
        carPartsShopAudit.setUpdateTime(DateUtils.getNowDate());
        return carPartsShopAuditMapper.updateCarPartsShopAudit(carPartsShopAudit);
    }

    /**
     * 批量删除汽配商入住审核
     *
     * @param carPartsShopAuditIds 需要删除的汽配商入住审核主键
     * @return 结果
     */
    @Override
    public int deleteCarPartsShopAuditByCarPartsShopAuditIds(Long[] carPartsShopAuditIds)
    {
        return carPartsShopAuditMapper.deleteCarPartsShopAuditByCarPartsShopAuditIds(carPartsShopAuditIds);
    }

    /**
     * 删除汽配商入住审核信息
     *
     * @param carPartsShopAuditId 汽配商入住审核主键
     * @return 结果
     */
    @Override
    public int deleteCarPartsShopAuditByCarPartsShopAuditId(Long carPartsShopAuditId)
    {
        return carPartsShopAuditMapper.deleteCarPartsShopAuditByCarPartsShopAuditId(carPartsShopAuditId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult isPassCarPartsShopAudit(IsPassCarPartsShopAuditParam isPassCarPartsShopAuditParam) {
        CarPartsShopAudit carPartsShopAudit = carPartsShopAuditMapper.selectCarPartsShopAuditByCarPartsShopAuditId(isPassCarPartsShopAuditParam.getCarPartsShopAuditId());
        if (carPartsShopAudit != null) {
            if ("1".equals(isPassCarPartsShopAuditParam.getAuditStatus()) && !"1".equals(carPartsShopAudit.getAuditStatus())) {
                // 生成汽配商保证金支付订单编号
                String shopOrderNo = RandomKit.genOrderId();
                carPartsShopAudit.setShopBandOrderNo("sbo" + shopOrderNo);
                carPartsShopAudit.setAuditStatus(isPassCarPartsShopAuditParam.getAuditStatus());
                int i = carPartsShopAuditMapper.updateCarPartsShopAudit(carPartsShopAudit);
                // 将汽配商审核通知添加到通知表中
                UserNotice userNotice = new UserNotice();
                userNotice.setNoticeType(1);
                userNotice.setContent("商家入驻申请审核通过");
                userNotice.setUserId(carPartsShopAudit.getUserId());
                userNotice.setChildType(13);
                userNotice.setSide(0);
                userNotice.setAuditType(1);
                userNotice.setSourceId(isPassCarPartsShopAuditParam.getCarPartsShopAuditId());
                userNoticeService.save(userNotice);
                if(i>0){
                    //查看是否需要支付保证金
                    Boolean isPay=plaPlatformSettingsService.isPayBaod(1);
                    User user = userService.getById(carPartsShopAudit.getUserId());
                    if(user==null){
                        throw new GlobalException("小程序用户不存在");
                    }
                    if(!isPay){//如果不需要支付保证金
                        carPartsShopAudit.setBondStatus("1");
                        carPartsShopAudit.setLoginPassword("123456");
                        carPartsShopAudit.setAccountNumber(user.getPhoneNumber());
                        //不需要支付保证金时,把支付订单设为空
                        carPartsShopAudit.setShopBandOrderNo("");
                        carPartsShopAudit.setLoginUrl(adminUrl);
                        int i1 = carPartsShopAuditMapper.updateById(carPartsShopAudit);
                        if(i1>0){
                            //根据汽配商入驻申请表id新增汽配商表
                            this.addCarPartsCity(carPartsShopAudit.getCarPartsShopAuditId());
                        }

                    }
                }
                return ApiResult.success();
            } else if ("2".equals(isPassCarPartsShopAuditParam.getAuditStatus())) {
                // 将汽配商审核通知添加到通知表中
                UserNotice userNotice = new UserNotice();
                userNotice.setNoticeType(1);
                userNotice.setContent("商家申请审核不通过，理由：" + isPassCarPartsShopAuditParam.getFailReason());
                userNotice.setUserId(carPartsShopAudit.getUserId());
                userNotice.setChildType(13);
                userNotice.setSide(0);
                userNotice.setAuditType(2);
                userNotice.setSourceId(isPassCarPartsShopAuditParam.getCarPartsShopAuditId());
                userNoticeService.save(userNotice);
                carPartsShopAudit.setAuditStatus(isPassCarPartsShopAuditParam.getAuditStatus());
                carPartsShopAudit.setFailReason(isPassCarPartsShopAuditParam.getFailReason());
                return ApiResult.success(carPartsShopAuditMapper.updateCarPartsShopAudit(carPartsShopAudit));
            } else {
                return ApiResult.error("审核失败");
            }
        } else {
            return ApiResult.error("审核失败");
        }
    }

    @Override
    public CarPartsShopAuditListVo selectCarPartsShopAuditDetailsByCarPartsShopAuditId(Long carPartsShopAuditId) {
        return carPartsShopAuditMapper.selectCarPartsShopAuditDetailsByCarPartsShopAuditId(carPartsShopAuditId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult allPassPassCarPartsShopAudit(Long[] carPartsShopAuditIds) {
        for(Long auditId:carPartsShopAuditIds){
            IsPassCarPartsShopAuditParam ipp = new IsPassCarPartsShopAuditParam();
            ipp.setAuditStatus("1");
            ipp.setCarPartsShopAuditId(auditId);
            isPassCarPartsShopAudit(ipp);
        }
        return ApiResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult allPassPassCarPartsShopAudit2(Long[] carPartsShopAuditIds) {
        if (carPartsShopAuditIds == null) {
            return ApiResult.error("请选择要通过的汽配商");
        }
        for (Long carPartsShopAuditId : carPartsShopAuditIds) {
            CarPartsShopAudit carPartsShopAudit = carPartsShopAuditMapper.selectCarPartsShopAuditByCarPartsShopAuditId(carPartsShopAuditId);
            if (carPartsShopAudit != null && carPartsShopAudit.getCertStatus()==3) {
                carPartsShopAudit.setCertStatus(1);
                int i = carPartsShopAuditMapper.updateCarPartsShopAudit(carPartsShopAudit);
                if(i>0){
                    //新增商家认证消息,系统通知类型为3,认证
                    shopNoticeService.insertShopSystemNotice(3,"你提交的认证信息审核已通过.",carPartsShopAuditId);
                }
            }
        }
        return ApiResult.success();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult isPassCarPartsShopAudit2(IsPassCarPartsShopCertAudit isPassCarPartsShopCertAudit) {
        CarPartsShopAudit carPartsShopAudit = carPartsShopAuditMapper.selectCarPartsShopAuditByCarPartsShopAuditId(isPassCarPartsShopCertAudit.getCarPartsShopAuditId());
        if (carPartsShopAudit == null) {
            return ApiResult.error("认证申请不存在");
        }
        if (carPartsShopAudit.getCertStatus()!=3) {
            return ApiResult.error("当前认证申请不是待审核认证的状态");
        }
        carPartsShopAudit.setCertStatus(isPassCarPartsShopCertAudit.getCertStatus());
        if(StringUtils.isNotEmpty(isPassCarPartsShopCertAudit.getCertMark())){
            carPartsShopAudit.setCertMark(isPassCarPartsShopCertAudit.getCertMark());
        }
        int i = carPartsShopAuditMapper.updateCarPartsShopAudit(carPartsShopAudit);
        if(i>0){
            String msgContent="";
            if(isPassCarPartsShopCertAudit.getCertStatus()==2){//不通过
                msgContent="你提交的认证信息审核不通过,";
                if(StringUtils.isNotEmpty(isPassCarPartsShopCertAudit.getCertMark())){
                    msgContent=msgContent+"理由:"+isPassCarPartsShopCertAudit.getCertMark();
                }
            }
            if(isPassCarPartsShopCertAudit.getCertStatus()==1){//通过
                msgContent="你提交的认证信息审核已通过.";
            }
            //新增商家认证消息,系统通知类型为3,认证
            shopNoticeService.insertShopSystemNotice(3,msgContent,isPassCarPartsShopCertAudit.getCarPartsShopAuditId());
        }
        return ApiResult.success(i);

    }

    /**
     *  //根据汽配商入驻申请表id新增汽配商表
     * @param carPartsShopAuditId
     * @return
     */
    @Override
    public int addCarPartsCity(Long carPartsShopAuditId) {
        CarPartsShopAudit carPartsShopAudit = this.getOne(new QueryWrapper<CarPartsShopAudit>().eq("car_parts_shop_audit_id", carPartsShopAuditId));
        //更新汽配商审核表中的信息
        User user = userService.getOne(new QueryWrapper<User>()
                .eq("user_id", carPartsShopAudit.getUserId()).eq("del_flag","0"));
        if (user == null) {
            throw new GlobalException("提交当前申请的用户不存在");
        }

        if (carPartsShopAudit != null) {
            //查询商家是否存在
            CarPartsShop one = carPartsShopService.getOne(new LambdaQueryWrapper<CarPartsShop>()
                    .eq(CarPartsShop::getCarPartsShopAuditId, carPartsShopAuditId)
                    .eq(CarPartsShop::getDelFlag,"0")
            );
            if(one==null){
                // 插入信息到商家表中
                Store store = new Store();
                store.setPhoneNumber(user.getPhoneNumber());
                store.setLoginPassword("123456");
                store.setNickName(user.getNickName());
                store.setAvatarUrl(user.getAvatarUrl());
                storeService.save(store);


                //插入汽配商表中的信息
                CarPartsShop carPartsShop = new CarPartsShop();
                BeanUtils.copyProperties(carPartsShopAudit,carPartsShop);
                carPartsShop.setCarPartsShopAuditId(carPartsShopAudit.getCarPartsShopAuditId());
                carPartsShop.setStoreId(store.getStoreId());
                carPartsShop.setIsPayBond("0");//1表示已经缴纳保证金,0不需要缴纳保证金
                boolean save = carPartsShopService.save(carPartsShop);

                // 在后台系统用户表中添加用户数据
                SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("phonenumber",user.getPhoneNumber()));
                if (sysUser == null) {
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setUserName(user.getPhoneNumber());
                    sysUser1.setNickName(user.getNickName());
                    sysUser1.setUserType("11");
                    sysUser1.setPhonenumber(user.getPhoneNumber());
                    sysUser1.setPassword("$2a$10$zAmI.N6FeP2Bo3oXFSz4aOJdhfVCZ.CxV6kgBd8ohUZu0jJ.mf3FG");
                    sysUser1.setAvatar(user.getAvatarUrl());
                    sysUser1.setCarPartsShopId(carPartsShop.getCarPartsShopId());
                    sysUser1.setMiniUserId(user.getUserId());
                    boolean save1 = sysUserService.save(sysUser1);

                    // 信息插入后台的用户角色关联表

                    SysUserRole userRole = sysUserRoleMapper.selectOne(new QueryWrapper<SysUserRole>().lambda()
                            .eq(SysUserRole::getUserId, sysUser1.getUserId()).eq(SysUserRole::getRoleId, 100));
                    if (userRole == null) {
                        SysUserRole userRole1 = new SysUserRole();
                        userRole1.setUserId(sysUser1.getUserId());
                        userRole1.setRoleId(100L);
                        int insert = sysUserRoleMapper.insert(userRole1);
                        return insert;
                    }
                }
            }

        }
        return 1;
    }
}
